<?php

namespace Osp\UserBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Osp\UserBundle\Entity\User;
use JMS\SecurityExtraBundle\Annotation\Secure; 

class UserController extends Controller
{
	/**
   	* @Secure(roles="ROLE_ADMIN")
   	*/
    public function userManagementAction()
    {

    	$error = null;
    	//Récupération des utilisateurs dans la base
	   	$repository = $this->getDoctrine()->getManager()->getRepository('OspUserBundle:User');
		$liste_users = $repository->findAll();

		if (!$liste_users) 
		{ 
			//throw $this->createNotFoundException('No users in the db');
			$error = "Aucun utilisateur dans la Base de données";
		}


		//Création du formulaire
		$user = new User();
		$user->setSalt(uniqid(mt_rand()));

		// On crée le FormBuilder grâce à la méthode du contrôleur
		$formBuilder = $this->createFormBuilder($user);

		$formBuilder
		->add('username', 'text')
		->add('password', 'password')
		->add('roles', 'text')
		->add('nom', 'text')
		->add('prenom', 'text')
		->add('adresse', 'text')
		->add('codePostal', 'text')
		->add('ville', 'text')
		->add('email', 'email')
		->add('telephone', 'text');

		$form = $formBuilder->getForm();

		//On récupère la requête
		$request = $this->get('request');


		//Si la requête est de type POST
		if($request->getMethod() == 'POST')
		{
			//user contient maintenant les valeurs du formulaire
			$form->bind($request);

			// Set encrypted password
			$encoder = $this->container->get('sha256salted_encoder');
			$password = $encoder->encodePassword($user->getPassword(), $user->getSalt());
			$user->setPassword($password);
			
			if($form->isValid())
			{
				$entityManager = $this->getDoctrine()->getManager();
				$entityManager->persist($user);
				$entityManager->flush();

				return $this->redirect($this->generateUrl('osp_user_homepage'));
			}

				else
				{
					return $this->render('OspUserBundle:User:errors.html.twig', array('error' => $form->getErrorsAsString()));
				}

		}

		else
		{
        	return $this->render('OspUserBundle:User:userManagement.html.twig', array('users' => $liste_users, 'form' => $form->createView(), 'error' => $error));
    	}
    }

    /**
   	* @Secure(roles="ROLE_ADMIN")
   	*/
    public function deleteUserAction($id) 
	{ 
		$entityManager = $this->getDoctrine()->getManager(); 
		$user = $entityManager->getRepository('OspUserBundle:User')->find($id); 

		if (!$user) 
			{ 
				throw $this->createNotFoundException('No user found for id '.$id); 
			} 

		$entityManager->remove($user); 
		$entityManager->flush(); 

		return $this->redirect($this->generateUrl('osp_user_homepage')); 
	}

	/**
   	* @Secure(roles="ROLE_ADMIN")
   	*/
	public function updateUserAction($id)
	{ 
		$entityManager = $this->getDoctrine()->getManager(); 
		$user = $entityManager->getRepository('OspUserBundle:User')->find($id); 

		if (!$user) 
			{ 
				throw $this->createNotFoundException('No user found for id '.$id);
			}


		// On crée le FormBuilder grâce à la méthode du contrôleur
		$formBuilder = $this->createFormBuilder($user);

		$formBuilder
		->add('username', 'text')
		->add('roles', 'text')
		->add('nom', 'text')
		->add('prenom', 'text')
		->add('adresse', 'text')
		->add('codePostal', 'text')
		->add('ville', 'text')
		->add('email', 'email')
		->add('password', 'password',array('required' => false))
		->add('telephone', 'text');

		$form = $formBuilder->getForm();

		//On récupère la requête
		$request = $this->get('request');


		//Si la requête est de type POST
		if($request->getMethod() == 'POST')
		{
			$oldpass = $user->getPassword();
			//user contient maintenant les valeurs du formulaire
			$form->bind($request);
			
			if($form->isValid())
			{
				//Si le mot de passe n'est pas vide
				if(!($user->getPassword() == ""))
				{
					// Set encrypted password
					$encoder = $this->container->get('sha256salted_encoder');
					$password = $encoder->encodePassword($user->getPassword(), $user->getSalt());
					$user->setPassword($password);
				}

				else
				{
					$user->setPassword($oldpass);
				}

				$entityManager = $this->getDoctrine()->getManager();
				$entityManager->flush();

				return $this->redirect($this->generateUrl('osp_user_homepage'));
			}

				else
				{
					return $this->render('OspUserBundle:User:errors.html.twig', array('error' => $form->getErrorsAsString()));
				}

		}	 

		return $this->render('OspUserBundle:User:userUpdate.html.twig', array('user' => $user, 'form' => $form->createView())); 
	}
}
